﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System.Globalization;
using System.Web;
using Microsoft.SharePoint.Utilities;
namespace DissingConsulting.CreateHostNamedSiteCollection
{
    public partial class CreateSiteCollectionPage : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var webapplication = GetWebapplications();
            UIWebApplications.DataSource = webapplication;
            UIWebApplications.DataBind();
        }
        protected IEnumerable GetWebapplications()
        { 
            foreach(var webapp in SPWebService.ContentService.WebApplications)
            {
                if(webapp.IisSettings[SPUrlZone.Default].ServerBindings.Any(i => string.IsNullOrEmpty(i.HostHeader)))
                    yield return webapp;
            }
        }
        protected void BtnCreateSite_Click(object sender, EventArgs e) 
        {
            if (Page.IsValid)
            {
                string ownerLogin = null;
                string ownerName = null;
                string ownerEmail = null;
                string secondaryContactLogin = null;
                string secondaryContactName = null;
                string secondaryContactEmail = null;


                PickerEntity entity = (PickerEntity)this.PickerOwner.ResolvedEntities[0];
                ownerLogin = entity.Key;
                ownerName = entity.DisplayText;
                ownerEmail = (string)entity.EntityData["Email"];
                if (this.PickerOwner2.ResolvedEntities.Count != 0)
                {
                    entity = (PickerEntity)this.PickerOwner2.ResolvedEntities[0];
                    secondaryContactLogin = entity.Key;
                    secondaryContactName = entity.DisplayText;
                    secondaryContactEmail = (string)entity.EntityData["Email"];
                }

                string sitetitle = TxtSiteName.Text.Trim();
                string sitecollectionUrl = TxtSiteName.Text;
                TemplatePicker picker = (TemplatePicker)InputFormTemplatePickerControl;
                uint nLCID = uint.Parse(picker.SelectedWebLanguage);
                int compatibilityLevel = int.Parse(picker.SelectedSiteCompatibilityLevel, CultureInfo.InvariantCulture);
                string webtemplate = picker.SelectedWebTemplate;
                string url = "/_admin/DissingConsulting.CHNSC/CreateSiteCollectionDone.aspx";
                string urlParm = string.Format("url={0}", sitecollectionUrl);
                using (SPLongOperation longOperation = new SPLongOperation(this.Page))
                {
                    longOperation.LeadingHTML = "Creating site collection. Please wait while the operation is running";
                    longOperation.Begin();

                    SPSite site = SelectedWebapplication.Sites.Add(sitetitle, this.TxtCreateSiteTitle.Text.Trim(), (this.TxtCreateSiteDescription.Text == null) ? null : this.TxtCreateSiteDescription.Text.Trim(), nLCID, compatibilityLevel, webtemplate, ownerLogin, ownerName, ownerEmail, secondaryContactLogin, secondaryContactName, secondaryContactEmail, true);
                    site.Dispose();

                    try
                    {
                        longOperation.End(url, SPRedirectFlags.Static, HttpContext.Current, urlParm);

                    }
                    catch
                    {
                        Page.Response.Flush();
                        SPUtility.Redirect(url, SPRedirectFlags.Static, HttpContext.Current, urlParm);
                    }

                }
            }
        }

        private SPWebApplication SelectedWebapplication
        {
            get
            {
                Guid webappid = new Guid(UIWebApplications.SelectedValue);
                return SPWebService.ContentService.WebApplications[webappid];
            }
        }

        protected void Validated_SiteUrl(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
        {
            if(SelectedWebapplication.Sites[TxtSiteName.Text] == null)
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }
    }
}
